<?php

namespace admin\controllers;

use Yii;
use admin\models\Retail;
use admin\models\AdminUser;
use admin\models\User;
use admin\models\RetailWithdraw;
use admin\models\RetailAccount;
use common\helpers\Hui;
use common\helpers\Html;
use common\helpers\StringHelper;
use admin\models\Order;

class RetailController extends \admin\components\Controller
{
    /**
     * @authname 代理商列表
     */
    public function actionList()
    {
        $query = (new Retail)->search();

        $html = $query->getTable([
            'admin_id',
            'account' => ['header' => '代理商账号', 'search' => true],
            // 'company_name' => ['type' => 'text', 'search' => true],
            'realname' => ['type' => 'text', 'search' => true],
            'tel' => ['type' => 'text', 'search' => true],
            'qq' => ['type' => 'text', 'search' => true],
            'point' => ['header' => '返点(%)'],
            'total_fee',
            // 'deposit' => ['type' => 'text'],
            'code',
            'created_at',
            ['header' => '操作', 'width' => '80px', 'value' => function ($row) {
                return Hui::primaryBtn('修改返点(0-'.config('web_point', 80).')', ['editPoint', 'id' => $row->admin_id], ['class' => 'editBtn']);
            }]
        ], [
            'addBtn' => ['saveRetail' => '添加代理商']
        ]);

        return $this->render('list', compact('html'));
    }

    /**
     * @authname 修改代理商返点%
     */
    public function actionEditPoint() 
    {
        $retail = Retail::findOne(get('id'));
        $user = User::find()->where(['admin_id' => $retail->admin_id])->orderBy('point DESC')->one();
        $point = $user?$user->point:0;
        $retail->point = post('point');
        if (($point + $retail->point) > intval(config('web_point', 80)) || is_int($retail->point) || $retail->point < 0) {
            return error('经纪人的返点不能超过'.config('web_point', 80).'%(设置返点为正整数)');
        }
        if ($retail->validate()) {
            $retail->update(false);
            return success();
        } else {
            return error($retail);
        }
    }

    /**
     * @authname 添加/编辑会员单位
     */
    public function actionSaveRetail($id = 0)
    {
        $model = Retail::findModel($id);

        if ($model->load()) {
            $model->code = StringHelper::random(6, 'n');
            $model->admin_id = time();
            if ($model->validate()) {
                $model->save(false);
                $admin = new AdminUser;
                $admin->username = $model->account;
                $admin->password = $model->pass;
                $admin->realname = $model->realname;
                if ($admin->saveAdmin()) {
                    $auth = Yii::$app->authManager;
                    $role = $auth->getRole('代理商管理');
                    $auth->assign($role, $admin->id);
                    $model->admin_id = $admin->id;
                    $model->update();
                } else {
                    $model->delete();
                    return error($admin);
                }
                return success();
            } else {
                return error($model);
            }
        }

        return $this->render('saveRetail', compact('model'));
    }
    /**
     * @authname 金额变化列表
     */
    public function actionFromAmount()
    {
        // test(u()->id);
        $query = (new Order)->fromAmountQuery()->orderby('order.created_at DESC');

        $html = $query->getTable([
            'user.id' => ['header' => '用户ID'],
            'user.nickname' => ['header' => '用户昵称'],
            'id' => ['header' => '订单ID'],
            'product.name',
            'profit' => function ($row) {
                if ($row['profit'] > 0) {
                    return '保证金 -'.$row['profit'];
                } elseif ($row['profit'] == 0) {
                    return '保证金 ' . $row['profit'];
                } else {
                    return '账户余额 ' . abs($row['profit']);
                }
                // $row['profit'] == 0?$row['profit']:-$row['profit']
            },
            'updated_at' => ['header' => '完成时间']
            ], [
            'searchColumns' => [
                'user.id' => ['header' => '用户ID'],
                // 'time' => ['header' => '审核时间', 'type' => 'dateRange']
            ],
            // 'ajaxReturn' => [
            //     'count' => $count
            // ]
        ]);
        return $this->render('fromAmount', compact('html'));
    }

    /**
     * @authname 代理商出金管理
     */
    public function actionWithdrawList()
    {
        $query = (new RetailWithdraw)->listQuery()->joinWith(['admin.retail'])->orderBy('retailWithdraw.created_at DESC');
        $countQuery = (new RetailWithdraw)->listQuery()->joinWith(['admin.retail'])->andWhere(['op_state' => RetailWithdraw::OP_STATE_PASS]);
        if (u()->power < AdminUser::POWER_ADMIN) {
            $query->andWhere(['admin_id' => u()->id]);
            $countQuery->andWhere(['admin_id' => u()->id]);
        }
        $count = $countQuery->select('SUM(amount) amount')->one()->amount ?: 0;

        $html = $query->getTable([
            'admin.username' => ['header' => '代理商账号'],
            'retail.total_fee',
            'amount' => '出金金额',
            'updated_at',
            'op_state' => ['search' => 'select'],
            ['header' => '操作', 'width' => '70px', 'value' => function ($row) {
                $string = '';
                if (u()->power >= AdminUser::POWER_ADMIN) {
                    if ($row['op_state'] == RetailWithdraw::OP_STATE_WAIT) {
                        $string = Hui::primaryBtn('代理商出金', ['retail/verifyWithdraw', 'id' => $row['id']], ['class' => 'layer.iframe']);
                    } else {
                        $string = Html::successSpan('已审核');
                    }
                }

                return $string .= Hui::primaryBtn('查看详细详细', ['retail/readWithdraw', 'id' => $row['id']], ['class' => 'layer.iframe']);
            }]
        ], [
            'searchColumns' => [
                'admin.username' => ['header' => '代理商账号'],
                'time' => ['header' => '审核时间', 'type' => 'dateRange']
            ],
            'addBtn' => ['withdraw' => '代理商体现申请'],
            'ajaxReturn' => [
                'count' => $count
            ]
        ]);
        

        return $this->render('withdrawList', compact('html', 'count'));
    }


    /**
     * @authname 代理商出金操作
     */
    public function actionVerifyWithdraw($id)
    {
        $model = RetailWithdraw::find()->with(['admin.retail', 'admin.retailAccount'])->where(['id' => $id])->one();

        if (req()->isPost) {
            $model->op_state = post('state');
            if ($model->update()) {
                if ($model->op_state == RetailWithdraw::OP_STATE_DENY) {
                    $model->admin->retail->total_fee += $model->amount;
                    $model->admin->retail->update();    
                }
                return success();
            } else {
                return error($model);
            }
        }

        return $this->render('verifyWithdraw', compact('model'));
    }

    /**
     * @authname 查看代理商出金详细
     */
    public function actionReadWithdraw($id)
    {
        $model = RetailWithdraw::find()->with(['admin.retail', 'admin.retailAccount'])->where(['id' => $id])->one();

        return $this->render('readWithdraw', compact('model'));
    }

    /**
     * @authname 代理商提现申请
     */
    public function actionWithdraw()
    {
        $model = new RetailWithdraw;
        $retailAccount = RetailAccount::findOne(u()->id);
        if (empty($retailAccount)) {
            $retailAccount = new RetailAccount;
        }

        $retail = Retail::find()->where(['account' => u()->username])->one();
        if (empty($retail)) {
            $amount = 0;
        } else {
            $amount = $retail->total_fee;
        }

        if ($model->load() && $retailAccount->load()) {
            if (empty($retail)) {
                return error('超级管理员无法提现！');
            }
            if ($retail->deposit < config('web_manager_deposit', 5000)) {
                return error('保证金低于' . config('web_manager_deposit', 5000) . '元，不能提现！');
            }
            $model->admin_id = $retailAccount->admin_id = u()->id;
            if (!$retailAccount->validate()) {
                return self::error($retailAccount);
            } else {
                $retailAccount = RetailAccount::findOne(u()->id);
                if (!empty($retailAccount)) {
                    $retailAccount->save(false);
                } else {
                    $retailAccount->insert(false);
                }
            }
            //提现额度不能超过80%
            $amount = $amount * config('admin_total_fee', 80) / 100; 
            if ($amount < $model->amount) {
                return error('提现额度不能超过总余额的' . config('web_manager_rate', 80) . '%！');
            }
            if ($amount <= 0 || $model->amount <= 0) {
                return error('提现金额违法！');
            }
            //每个月只能成功体现一次
            $start = date('Y-m-01 00:00:00', strtotime(date('Y-m-d')));
            $end = date('Y-m-01 00:00:00', strtotime('+1 month'));
            $retailWithdraw = RetailWithdraw::find()->where(['admin_id' => u()->id])->andWhere(['between', 'created_at', $start, $end])->andWhere(['<>', 'op_state', RetailWithdraw::OP_STATE_DENY])->one();
            if (!empty($retailWithdraw)) {
                return error('每个月只能申请提现一次！');
            }

            if ($model->save()) {
                $retail->total_fee -= $model->amount;
                $retail->save(false);

                return success();
            } else {
                return error($model);
            }
        }

        return $this->render('withdraw', compact('model', 'retailAccount', 'amount'));
    }
}
